<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeDialog" @open="openDialog">
    <!-- 这里准备复选框 -->
    <!--
       1视图->数据 当我们通过选中操作 选中项的label值会自动放到checkList中
       2 数据->视图 checkList中如果有值 checkList谁的label在里面存在 它就会显示选中状态
     -->
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>

    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="confirm">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleApi, assignRoles, getUserinforAPI } from '@/api'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    curId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 多选框数据
      checkList: [],
      roleList: []
    }
  },
  methods: {
    closeDialog() {
      this.$emit('close-assign-dialog')
      this.checkList = []
      this.roleList = []
    },
    // 打开弹框获取数据
    async openDialog() {
      // 获取角色列表
      const res = await getRoleApi({ page: 1, pagesize: 100 })
      this.roleList = res.data.rows
      // 获取个人信息
      const resUserinfo = await getUserinforAPI(this.curId)
      this.checkList = resUserinfo.data.roleIds
    },
    // 弹框点击确定
    // { id:当前用户id, roleIds:选中的角色id组成的数组 }
    async confirm() {
      await assignRoles({
        id: this.curId,
        roleIds: this.checkList
      })
      this.$message.success('分配角色成功')
      this.closeDialog()
    }
  }
}
</script>
